package com.polaris.live.ui.set.cover

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R.drawable
import com.polaris.live.common.R.drawable.ic_correct
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.AppConst.CoverPhoto.ISREADYUP
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.LogExt
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.ActivitySetLiveImageBinding
import com.polaris.live.dialog.common.CommonSureDetailDialog
import com.polaris.live.dialog.common.CommonSureDialog
import com.polaris.live.dialog.common.ConfirmCanalDialog
import com.polaris.live.interface_bag.S3UploadCallback
import com.polaris.live.popup.SelectImagePopup
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CropUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.getIntOrString
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.viewmodel.SetLiveImageViewModel
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

/**
 * SetLiveImageActivity     进入此页面需要传一个type告诉我你是从哪里来的
 *
 * @author Created by 半仙 on 2023/9/4/004 15:00
 */
class SetLiveImageActivity : BaseVbActivity<SetLiveImageViewModel, ActivitySetLiveImageBinding>() {

    companion object {

        const val ONCLICK = LiveConst.Type.CLIENT_DEFAULT  //只要不是开启直播或者加入直播打电话啥的都是-1 可以理解为主动点进来的都是-1
    }

    private var mLiveType: Int = ONCLICK
    private var mNickname: String = ""

    //是否提交过封面照
    private var mIsSubmit = false

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBar(mBinding.llTitle)
            .navigationBarDarkIcon(true)
            .statusBarDarkFont(true)
            .init()
    }

    //封面上传后的机审过没过
    private var mIsUpLoad = false
    override fun initView(savedInstanceState: Bundle?) {
        ViewUtils.setMargin(mBinding.done, bottomMargin = NavigationBarUtils.getNavigationBarHeight(this))
        initListener()

        initObsever()

        mLiveType = intent.getIntOrString("type", ONCLICK)
        mNickname = intent.getStringExtra("name") ?: ""

        if (!CommonUtils.isMan(UserManager.getUser().sex)) {
            mBinding.apply {
                ivSetCover1.setImageResource(drawable.set_live_cover_woman_1)
                ivSetCover2.setImageResource(drawable.set_live_cover_woman_2)
                ivSetCover3.setImageResource(drawable.set_live_cover_woman_3)
                ivSetCover4.setImageResource(drawable.set_live_cover_woman_4)
                ivSetCover5.setImageResource(drawable.set_live_cover_woman_5)
                ivSetCover6.setImageResource(drawable.set_live_cover_woman_6)
            }
        }
        mViewModel.userCover()
    }

    private fun initObsever() {
        //上传背景照
        mViewModel.mUploadLiveData.observe(this) { resultState ->
            mBinding.passwordDangerous.visibility = View.VISIBLE
            mBinding.setLiveImageIv.visibility = View.VISIBLE
            parseState(resultState, {
                if (it.status == ISREADYUP) {
                    mIsUpLoad = true
                    mBinding.done.alpha = 1.0f
                    mBinding.done.isEnabled = true
                    mBinding.setLiveImageDetail.text = StringUtils.getString(string.ai_is_ok)
                    mBinding.setLiveImageDetail.setTextColor(Color.parseColor("#29D000"))
                    mBinding.setLiveImageIv.setImageResource(ic_correct)
                    EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                }
            }, {
                if (it.errCode == CommonConst.ErrorCode.COVER_UP_ERROR_DIALOG1 || it.errCode == CommonConst.ErrorCode.COVER_UP_ERROR_DIALOG2) {
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asCustom(CommonSureDialog(this, it.errorMsg))
                        .show()
                }

                mIsUpLoad = false
                mBinding.setLiveImageDetail.text = it.errorMsg
                mBinding.setLiveImageDetail.setTextColor(Color.parseColor("#FE4F3C"))
                mBinding.setLiveImageIv.setImageResource(drawable.ic_delete_account_warn_red)
            })
        }
        //获取用户背景照
        mViewModel.mUserCoverLiveData.observe(this) { resultState ->
            parseState(resultState, {
                val coverPhoto = UserManager.getUser().coverPhoto
                if (coverPhoto != null) {
                    if (coverPhoto.hasCoverPhoto && it.url != null) {
                        showUrl(it.url)
                    } else if (coverPhoto.hasCoverPhoto) {
                        mBinding.passwordDangerous.visibility = View.VISIBLE
                    } else {
                        if (it.url != null) {
                            showUrl(it.url)
                        }
                    }
                }
            })
        }
        //提交封面照片
        mViewModel.mSubmitLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (mLiveType == LiveConst.Type.LIVE_AND_MATCH || mLiveType == LiveConst.Type.ONLY_MATCH) {
                    ToastGravity.showGravity(StringUtils.getString(string.cover_loading))
                }

                EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                mIsSubmit = true
                if (mLiveType == ONCLICK) {
                    finish()
                } else {
                    goStartLive()
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
        //上传封面预检查
        mViewModel.coverUploadLiveData.observe(this) { resultState ->
            parseState(resultState, {
                XPopup.Builder(this)
                    .moveUpToKeyboard(false)
                    .isDestroyOnDismiss(true)
                    .asCustom(SelectImagePopup(this, onSelectIt = { type ->
                        when (type) {
                            SelectImagePopup.CAMERA -> {
                                CropUtils.startCamera(this, { result ->
                                    CropUtils.startCrop(this, result)
                                }, {
                                })
                            }

                            else -> {
                                CropUtils.startAlbum(this, {
                                    uploadPhoto(it)
                                }, {})
                            }
                        }
                    }))
                    .show()
            }, {
                XPopup.Builder(this)
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        CommonSureDetailDialog(
                            this,
                            StringUtils.getString(string.warning),
                            it.errorMsg,
                            StringUtils.getString(string.ok)
                        )
                    )
                    .show()
            })
        }
    }

    private fun initListener() {
        mBinding.setLiveSelect.setOnSingleClickListener {
            mViewModel.coverPhotosUpload()
        }


        mBinding.done.setOnSingleClickListener {
            if (mBinding.done.alpha == 1.0f) {
                mViewModel.submitPhoto()
            } else {
                ToastGravity.showGravity(getString(string.Please_upload_a_cover_photo))
            }
        }
        mBinding.bvTitle.setOnLeftClientListener {
            isUpLoad()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            data?.let { result ->
                val file = UriUtils.uri2File(UCrop.getOutput(result))
                file?.let { uploadFile ->
                    uploadPhoto(uploadFile.absolutePath)
                }
            }
        } else if (resultCode == RESULT_CANCELED && requestCode == UCrop.REQUEST_CROP) {
            CropUtils.startCamera(this, { result ->
                CropUtils.startCrop(this, result)
            }, {
            })
        }
    }

    override fun onBackPressed() {
        isUpLoad()
    }

    private fun isUpLoad() {
        if (mIsUpLoad) {
            XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .asCustom(
                    ConfirmCanalDialog(
                        this,
                        StringUtils.getString(string.is_save_cover),
                        StringUtils.getString(string.submit_and_back),
                        onConfirmCallback = {
                            if (!mIsSubmit) {
                                mLiveType = ONCLICK
                                mViewModel.submitPhoto()
                            }
                        },
                        onCanalCallback = {
                            finish()
                        }
                    )
                ).show()
        } else {
            finish()
        }
    }

    private fun showUrl(url: String) {
        Glide.with(this@SetLiveImageActivity)
            .load(ImageUtils.imgPath(url))
            .transform(RoundedCorners(8.dp))
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(mBinding.selectImage)
        mBinding.selectImage.visibility = View.VISIBLE
        mBinding.ivUpimage.visibility = View.VISIBLE
    }

    @SuppressLint("WrongConstant")
    private fun goStartLive() {
        StartLiveProxy.builder(this).startLive(mViewModel, mLiveType) {
            finish()
        }
    }

    private fun uploadPhoto(photoUrl: String) {
        mBinding.passwordDangerous.visibility = View.INVISIBLE
        mBinding.done.alpha = AppConst.NOTCLICK
        mBinding.done.isEnabled = false

        showLoading(waitTime = 0)

        ImageUtils.s3Upload(
            photoUrl,
            AppConst.UpLoad.COVER_PHOTO,
            1024,
            callback = object : S3UploadCallback {
                override fun onSuccess(
                    url: String,
                    size: Pair<Int, Int>?,
                ) {
                    lifecycleScope.launch {
                        Glide.with(this@SetLiveImageActivity).load(photoUrl)
                            .skipMemoryCache(true)
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .into(mBinding.selectImage)
                        mBinding.selectImage.visibility = View.VISIBLE

                        mBinding.passwordDangerous.visibility = View.VISIBLE
                        mBinding.setLiveImageIv.visibility = View.GONE
                        mBinding.setLiveImageDetail.text =
                            StringUtils.getString(string.upload_succee)
                    }

                    mViewModel.upLoadImage(url)
                }

                override fun onFailure(t: Throwable) {
                    LogExt.logE("--net", t)

                    ToastGravity.showGravity(t.message)

                    dismissLoading()
                }
            })
    }
}